/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\StatementOfAccount\SendStatementOfAccount\components\StatementOfAccountInfo2.tsx
 * @Date: 2022-03-15 10:26:18
 * @LastEditTime: 2023-05-08 16:01:52
 */

import React from 'react'
import { UdTable, columnRenders, http, IUdColumn, UdModal, UdToolbar } from '@/lib'
import { InputNumber, message, Modal, Progress, Switch, Button, Spin } from 'antd'
import apis from '@/apis/StatementOfAccount/index'
import { downBlobFile } from '@/utils/methods'
import './style.scss'
export default class StatementOfAccountInfo extends React.Component<IProps> {
  state: IState = {
    percent: 0,
    dataSource: [],
    pagination: {},
    checked: false,
    selectedRowKeys: [],
    selectedRows: [],
    loading: false,
    downloading: false,
  }

  render() {
    let { pagination, loading, dataSource, selectedRowKeys, checked, percent } = this.state
    let { distributorList } = this.props
    return (
      <>
        <Spin spinning={this.state.downloading}>
          <div style={{ marginBottom: '10px' }}>
            <div>
              <span style={{ color: '#999', marginRight: '10px' }}>过滤与上期对账金额相同的经销商</span>
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                defaultChecked={checked}
                onClick={() => {
                  this.setState(
                    (preState: IState) => {
                      return {
                        checked: !preState.checked,
                        dataSource: [],
                        selectedRowKeys: [],
                        selectedRows: [],
                        pagination: {},
                      }
                    },
                    () => {
                      this.getTableData()
                    }
                  )
                }}
              />
            </div>
            <div style={{ width: '100%', overflow: 'hidden', marginBottom: '10px' }}>
              <span style={{ color: '#999', marginRight: '10px' }}>
                {`进度${dataSource.length}/${distributorList.length}条`}
              </span>
              <Progress percent={percent} />
            </div>
            <UdToolbar
              other={
                <Button type="primary" onClick={this.exportTableExcel}>
                  导出
                </Button>
              }
            ></UdToolbar>
          </div>
          <UdTable
            rowKey="id"
            scroll={{ x: true }}
            loading={loading}
            columns={this.calcColumns()}
            dataSource={dataSource}
            pagination={pagination}
            rowSelection={{
              selectedRowKeys: selectedRowKeys,
              onChange: this.onSelectChange,
              onSelectAll: this.onSelectAll,
            }}
            onChange={paginationOpt => {
              this.setState({ pagination: paginationOpt })
            }}
          />
        </Spin>
      </>
    )
  }

  componentDidMount() {
    this.getTableData()
  }

  onSelectChange = (selectedRowKeys: number[], selectedRows: Record<string, any>[]) => {
    this.setState({ selectedRowKeys, selectedRows })
  }

  onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      const { dataSource } = this.state
      this.setState({ selectedRows: dataSource, selectedRowKeys: dataSource.map(({ id }) => id) })
    } else {
      this.setState({ selectedRows: [], selectedRowKeys: [] })
    }
  }

  /**导出 */
  private exportTableExcel = () => {
    let { selectedRows } = this.state
    let { letterName } = this.props.values
    if (selectedRows.length === 0) {
      message.warning('请选择数据')
      return
    }
    this.setState({ downloading: true })
    let params = selectedRows.map(item => {
      let obj = { ...item }
      obj.letterName = letterName

      let keys = Object.keys(obj)
      let columnKeys = keys.filter(key => key.includes('value_'))
      if (columnKeys.length > 0) {
        obj.values = []
        for (let key of columnKeys) {
          let values: string[] = key.split('_')
          obj.values.push(`${values[2]}_${obj[key]}`)
        }
        obj.values = obj.values.toString()
      }
      return obj
    })
    http
      .post(apis.excelLetterLaunchInfo, params, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `对账函信息`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private inputChange = (value, record, field): void => {
    let { dataSource } = this.state
    let index = dataSource.findIndex(item => item.id === record.id)
    let newDataSource = [...dataSource]
    newDataSource[index][field] = value
    this.setState({ dataSource: newDataSource })
  }

  private renderInput = (text, record, field): any => {
    return (
      <InputNumber
        style={{ width: '100%' }}
        value={text}
        step={'0.01'}
        min={0}
        formatter={value => {
          const reg = /^(-)*(\d+)\.(\d\d).*$/
          const val = String(value).replace(reg, '$1$2.$3')
          return val
        }}
        parser={value => {
          const reg = /^(-)*(\d+)\.(\d\d).*$/
          const val = String(value).replace(reg, '$1$2.$3')
          return val
        }}
        onChange={value => this.inputChange(value, record, field)}
      />
    )
  }

  private calcColumns = () => {
    let { dataSource } = this.state
    let recordItem = dataSource[0]
    let restColumn: IUdColumn<any>[] = []
    if (recordItem) {
      let keys = Object.keys(recordItem)
      let columnKeys = keys.filter(key => key.includes('value_'))
      for (let key of columnKeys) {
        let values: string[] = key.split('_')
        restColumn.push({
          title: values[1],
          key: values[1],
          dataIndex: values.join('_'),
          minWidth: '70px',
          render: (text: any, record: any, index: number) => {
            if (values[3] === '1') {
              return this.renderInput(text, record, values.join('_'))
            } else {
              return text
            }
          },
        })
      }
    }
    let columns: IUdColumn<any>[] = [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: '50px',
        render: (text, reoled, index) => index + 1,
      },
      { title: '经销商编码', key: 'dealerCode', dataIndex: 'dealerCode', minWidth: '70px' },
      { title: '经销商名称', key: 'dealerName', dataIndex: 'dealerName', minWidth: '160px' },
      { title: '品牌公司', key: 'brandName', dataIndex: 'brandName', minWidth: '160px' },
      ...restColumn,
      { title: '截止日期', key: 'launchTime', dataIndex: 'launchTime', minWidth: '60px' },
      {
        title: '操作',
        dataIndex: 'operate',
        width: '130',
        fixed: 'right',
        render: columnRenders.operate([
          {
            title: '删除',
            action: (text, record) => {
              Modal.confirm({
                title: '删除',
                content: `确定删除${record.brandName}吗`,
                okType: 'danger',
                onOk: () => {
                  this.setState((preState: IState) => {
                    let dataSource = preState.dataSource.filter(item => item.id !== record.id)
                    return {
                      dataSource,
                      selectedRowKeys: preState.selectedRowKeys.filter(item => item !== record.id),
                      selectedRows: preState.selectedRows.filter(item => item.id !== record.id),
                      pagination: {
                        current: 1,
                        pageSize: 5,
                        total: dataSource.length ?? 0,
                        showSizeChanger: true,
                        pageSizeOptions: ['5', '10', '20', '30', '40'],
                        showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
                      },
                    }
                  })
                },
              })
            },
          },
          //*后端能力不够 说做不了 2022-4-22
          // {
          //   title: '预览',
          //   action: (text, record) => this.handTemplateView(record),
          // },
        ]),
      },
    ]
    return columns
  }

  private handTemplateView = (record: { modelUrl: string; modelFileName: string }): void => {
    const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
    const { modelUrl, modelFileName } = record
    if (rex.test(modelUrl)) {
      UdModal.open({
        title: modelFileName,
        width: '80%',
        bodyStyle: { padding: '0' },
        content: (
          <div style={{ height: '700px', overflow: 'hidden' }}>
            <iframe
              title={modelFileName}
              src={`https://view.officeapps.live.com/op/view.aspx?src=${modelUrl}`}
              width="100%"
              height="100%"
              frameBorder="0"
              style={{ border: 'none' }}
              seamless
            ></iframe>
          </div>
        ),
        footer: null,
      })
    } else {
      message.error('附件URL无效')
    }
  }

  private getTableData = async () => {
    let { checked } = this.state
    const { distributorList = [] } = this.props
    const { brandCode, launchTime, templateModelId, letterName } = this.props.values
    for (let item of distributorList) {
      let params = {
        brandCode,
        type: Number(checked),
        letterName,
        launchTime,
        templateModelId,
        agentRspVoList: [item],
      }
      try {
        let list: any = await http.post(apis.getLetterLaunchInfo, params)
        const dataSource = list?.data ?? []
        this.setState(
          preState => ({ dataSource: [...preState['dataSource'], ...dataSource] }),
          () => {
            let percent = Math.round((this.state.dataSource.length / distributorList.length) * 100)
            this.setState({
              percent,
              pagination: {
                current: 1,
                pageSize: 5,
                total: this.state.dataSource.length ?? 0,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '20', '30', '40'],
                showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
              },
            })
          }
        )
      } catch (error) {
        console.error(error)
      }
    }
    // let params = {
    //   brandCode,
    //   type: Number(checked),
    //   letterName,
    //   launchTime,
    //   templateModelId,
    //   agentRspVoList: distributorList,
    // }
    // try {
    //   let list: any = await http.post(apis.getLetterLaunchInfo, params)
    //   const dataSource = list?.data ?? []
    //   this.setState({
    //     dataSource,
    //     loading: false,
    //     pagination: {
    //       current: 1,
    //       pageSize: 5,
    //       total: dataSource.length ?? 0,
    //       showSizeChanger: true,
    //       pageSizeOptions: ['5', '10', '20', '30', '40'],
    //       showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
    //     },
    //   })
    // } catch (error) {
    //   this.setState({
    //     loading: false,
    //   })
    // }
  }

  private onOk = e => {
    let { selectedRows } = this.state
    let { letterName } = this.props.values
    if (selectedRows.length === 0) {
      message.warning('请选择数据')
      return
    }
    e.drawerBtnLoading()
    let params = selectedRows.map(item => {
      let obj = { ...item }
      obj.letterName = letterName

      let keys = Object.keys(obj)
      let columnKeys = keys.filter(key => key.includes('value_'))
      if (columnKeys.length > 0) {
        obj.values = []
        for (let key of columnKeys) {
          let values: string[] = key.split('_')
          obj.values.push(`${values[2]}_${obj[key]}`)
        }
        obj.values = obj.values.toString()
      }
      return obj
    })
    http
      .post(apis.saveLetterLaunchInfo, params)
      .then(() => {
        message.success('操作成功')
        e.close()
        this.props.history.push('/statementOfaccount/statementOfAccountRecord')
      })
      .catch(err => {
        e.drawerBtnLoadingHide()
        console.error(err)
      })
  }
}

interface IProps {
  distributorList: Record<string, any>[]
  values: Record<string, any>
  history: any
}

interface IState {
  pagination: Record<string, any>
  dataSource: Record<string, any>[]
  loading: boolean
  downloading: boolean
  checked: boolean
  selectedRowKeys: number[]
  selectedRows: Record<string, any>[]
  searchValues?: {}
  percent: number
}
